#题目模块
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models import Problem
from schemas import ProblemCreate, ProblemOut
from typing import List

router = APIRouter()

# 增：添加题目
@router.post("/", response_model=ProblemOut)
def create_problem(problem: ProblemCreate, db: Session = Depends(get_db)):
    db_problem = Problem(**problem.dict())
    db.add(db_problem)
    db.commit()
    db.refresh(db_problem)
    return db_problem

# 查：获取所有题目
@router.get("/", response_model=List[ProblemOut])
def get_problems(db: Session = Depends(get_db)):
    return db.query(Problem).all()

# 查：按id获取题目
@router.get("/{problem_id}", response_model=ProblemOut)
def get_problem(problem_id: int, db: Session = Depends(get_db)):
    problem = db.query(Problem).filter(Problem.id == problem_id).first()
    if not problem:
        raise HTTPException(status_code=404, detail="题目不存在")
    return problem

# 改：更新题目
@router.put("/{problem_id}", response_model=ProblemOut)
def update_problem(problem_id: int, new_data: ProblemCreate, db: Session = Depends(get_db)):
    problem = db.query(Problem).filter(Problem.id == problem_id).first()
    if not problem:
        raise HTTPException(status_code=404, detail="题目不存在")
    for key, value in new_data.dict().items():
        setattr(problem, key, value)
    db.commit()
    db.refresh(problem)
    return problem

# 删：删除题目
@router.delete("/{problem_id}")
def delete_problem(problem_id: int, db: Session = Depends(get_db)):
    problem = db.query(Problem).filter(Problem.id == problem_id).first()
    if not problem:
        raise HTTPException(status_code=404, detail="题目不存在")
    db.delete(problem)
    db.commit()
    return {"message": "题目已删除"}
